package logic

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/config"
)

func makeRedisKey(ctx context.Context, key string) string {
	return fmt.Sprintf("%s:%s", headInfo.GetBusinessCode(ctx), key)
}

func BuildRedisKey(ctx context.Context, userId int64, isAdmin bool, Business, Source string) string {
	key := strconv.FormatInt(userId, 10) + "_" + Business + "_" + Source
	if isAdmin {
		key += "_admin"
	} else {
		key += "_user"
	}
	return makeRedisKey(ctx, key)
}

func GetTokenRedis(ctx context.Context, conf config.RedisConf, userId int64, isAdmin bool, Business, Source string) string {
	rdb := GetRedisClient(conf)
	key := BuildRedisKey(ctx, userId, isAdmin, Business, Source)
	token, err := rdb.Get(ctx, key).Result()
	if err != nil {
		return ""
	}
	return token
}

func SetTokenRedis(ctx context.Context, conf config.RedisConf, userId int64, isAdmin bool, Business, Source string, sgin string) error {
	rdb := GetRedisClient(conf)
	key := BuildRedisKey(ctx, userId, isAdmin, Business, Source)
	_, err := rdb.Set(ctx, key, sgin, 60*60*24*time.Second).Result()
	if err != nil {
		return err
	}
	return nil
}
